package com.xu.sso.client.api.utils;

import com.xu.sso.client.api.model.request.ApiRequest;
import com.xu.sso.client.api.model.response.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import java.util.UUID;

public class SignUtil {

    private static Logger log = LoggerFactory.getLogger(SignUtil.class);

    public static ApiRequest sign(ApiRequest request, String key) {
        StringBuilder value = new StringBuilder();
        String requestId = UUID.randomUUID().toString();
        value.append("requestId=").append(requestId)
                .append("&appId=").append(request.getAppId())
                .append("&method").append(request.getMethod())
                .append("$content=").append(request.getContent())
                .append("&key=").append(key);
        try {
            String sign = DigestUtils.md5DigestAsHex(value.toString().getBytes("utf-8"));
            request.setSign(sign);
            request.setRequestId(requestId);
            return request;
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>>SignUtil.sign error===={}", e);
        }
        return null;
    }

    public static boolean verifySign(ApiResponse response, ApiRequest request, String key) {
        try {
            StringBuilder value = new StringBuilder();
            value.append("responseId=").append(response.getResponseId())
                    .append("&appId=").append(request.getAppId())
                    .append("&method").append(request.getMethod())
                    .append("$content=").append(response.getContent())
                    .append("&key=").append(key);
            String sign = DigestUtils.md5DigestAsHex(value.toString().getBytes("utf-8"));
            if (sign.equals(response.getSign())) {
                return true;
            }
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>>SignUtil.verifySign error===={}", e);
        }
        return false;
    }

}
